import React, { ReactNode } from 'react';
import { useDrag } from 'react-dnd';

interface SourceBoxProps {
  data: any;
  onEndDrag?: (dropData: any, dragItem: any) => void;
  children: ReactNode;
  hidden?: boolean;
}

export default function SourceBox(props: SourceBoxProps) {
  const { children, data, onEndDrag, hidden } = props;

  const [collected, drag, dragPreview] = useDrag(() => ({
    type: 'Item',
    item: { ...data },
    collect(monitor) {
      return {
        isDragging: monitor.isDragging(),
      };
    },
    end(props, monitor) {
      const item = monitor.getItem();
      const result = monitor.getDropResult();
      // 确定组件已经放置到右侧区域，有结果返回的时候，调用新增组件的方法
      if (monitor.didDrop() && result) {
        onEndDrag?.(result, item);
      }
    },
  }));

  return (
    <span
      ref={drag}
      style={{ opacity: collected.isDragging ? '0.5' : '1' }}
      hidden={collected.isDragging && hidden}
    >
      {children}
    </span>
  );
}
